<script setup lang='ts'>
import { onMounted, reactive, ref } from 'vue';
import { permissionApi } from '@/api/controller';
import { ToastSuccess, Toastloading } from '@/utils/public';
import ruleform from './components/ruleform.vue';
import { ElMessageBox } from 'element-plus';
const ruleformRef = ref(),
      tableRef = ref();
const action = reactive({
  total: 0,
  tree_id:-1,
  list: [] as any[],
})
const listQuery = reactive({
  page: 1,
  limit: 20,
  sort: '+id'
})
const handelRuleForm = (row: any = {}) => {
  ruleformRef.value.openDialog(row)
}
const handleDelete = (row: any = {}) => {
  ElMessageBox.confirm('确认删除该权限吗?', '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const loading = Toastloading();
      await permissionApi.deletePermission(row.id)
      loading.close();
      ToastSuccess('删除成功!');
      getList();
    }).catch(() => { })
}
const load = async (tree: { id: any; }, treeNode: any, resolve: (arg0: any) => void) => {
  const { id } = tree
  action.tree_id = id
  const data = await getTreeInfo(id)
  resolve(data)
}
const getTreeInfo = async (tree_id=-1)=>{
  if(tree_id == -1) return console.error('tree_id error')
  const res = await permissionApi.getPermission(tree_id)
  return res.data
}

const getList = async () => {
  const loading = Toastloading();
  const response = await permissionApi.getPermissions(listQuery)
  action.list = response.data.data
  loading.close()
}
onMounted(() => {
  getList()
})
</script>

<template>
  <div class="xm-content">
    <div class="xm-headTab">
      <el-button type="primary" @click="handelRuleForm()">新增</el-button>
    </div>
    <el-table class="xm-main" ref="tableRef" :load="load" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :data="action.list"
      row-key="id" border lazy>
      <el-table-column prop="id" label="ID" width="180" />
      <el-table-column align="center" prop="name" label="权限" width="180" />
      <el-table-column prop="desc" align="center" label="描述" />
      <el-table-column align="center" prop="created_at" label="创建时间" />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button type="primary" @click="handelRuleForm(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.status != 'deleted'" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <ruleform ref="ruleformRef" @updateList="getList" />
  </div>
</template>

<style lang='scss' scoped></style>